import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { HttpProvider } from '../../providers/http/http';
import { StorageProvider } from '../../providers/storage/storage';
import { DialogProvider } from '../../providers/dialog/dialog';
import { EventProvider } from '../../providers/event/event';
import { JpushProvider } from '../../providers/jpush/jpush';
import { JmessageProvider } from '../../providers/jmessage/jmessage';

/**
 * Generated class for the LoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
	selector: 'page-login',
	templateUrl: 'login.html',
})
export class LoginPage {

	private inputViewModel = {
		username: '',
		password: ''
	};

	constructor(
		public navCtrl: NavController,
		public navParams: NavParams,
		public http: HttpProvider,
		public storage: StorageProvider,
		public dialog: DialogProvider,
		public event: EventProvider,
		public jpush: JpushProvider,
		public jmessage: JmessageProvider) {

	}

	ionViewDidLoad() {
		console.log('ionViewDidLoad LoginPage');
		//最近一次登录账户显示
		this.storage.getStorage("last").then(val => {
			if (val != undefined) {
				this.inputViewModel.username = val['username'];
				this.inputViewModel.password = val['password'];
			}
		});
		//注册登录事件
		this.event.bindEvents(this.event.EVENT_LOGIN, (val) => {
			//执行登录检查
			this.checkLogin();
		});
		//发送登录事件
		this.event.sendEvents(this.event.EVENT_LOGIN, {});
	}
	/*界面销毁*/
	ionViewWillUnload() {
		this.event.unbindEvents(this.event.EVENT_LOGIN, function () { });
	}

	/*登录校验*/
	inputCheck() {
		if (this.inputViewModel.username == "") {
			this.dialog.showAlert("提示", "请输入用户名");
			return false;
		}
		if (this.inputViewModel.password == "") {
			this.dialog.showAlert("提示", "请输入密码");
			return false;
		}
		return true;
	}
	/*检查登录*/
	checkLogin() {
		this.storage.getStorage("user").then(val => {
			if (val == undefined) {
				this.navCtrl.popToRoot(); //显示登录
			} else {
				this.navCtrl.push("TabsPage"); //登录成功
			}
		});
	}
	/*登录操作*/
	loginOnSuccess() {
		//正式
		if(this.inputCheck()) {
			//请求方式如下
			let params = {
				username: this.inputViewModel.username,
				password: this.inputViewModel.password
			};
			this.http.postJson('center', 'login', params, true).then(res => {
				if (res['data']) {
					//注册信息
					//let registdata = { "username": res['data']['username'], "password": res['data']['password'], "nickname": res['data']['nickname'] };
					//this.jmessage.regist(registdata);
					//this.jpush.addLocalNotification();
					//登录成功
					this.storage.saveStorage('user', { 'user_id': res['data']['id'] }).then(success => {
						//刷新当前数据
						this.event.sendEvents(this.event.EVENT_LOGIN, {});
					});
					//保存最终登录
					this.storage.saveStorage("last", params);
				} else {
					this.dialog.showAlert("提示", '用户名或密码错误');
				}
			});
		}
	}
}